package com.hz.config;

import com.hz.pojo.Advertising;
import com.hz.service.AdvertisingService;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Configuration      //1.主要用于标记配置类
@EnableScheduling   // 2.开启定时任务
public class AdvertisingTrafficConfig {
    @Resource
    private AdvertisingService advertisingService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //3.添加定时任务  每天凌晨2点更新
    @Scheduled(cron = "0 0 2 * * ?")
    public void configureTasks() {
        //定义一个集合 获取所有广告对象
        List<Advertising> advertisingList = null;
        Long advertising_id = 0L;
        Long traffic = 0L;
        try {
            advertisingList = advertisingService.getAll();
            for (Advertising advertising : advertisingList) {
                //循环从获取的集合中 获取广告id
                advertising_id = advertising.getAdvertising_id();
                //利用广告id去Redis中取出相应的浏览量 转成Long类型
                traffic = Long.parseLong(stringRedisTemplate.opsForValue().get("advertising_id"));
            }
            //调用方法，根据广告id修改数据库中浏览量的值（浏览量的值是从Redis中获取）
            advertisingService.updTrafficById(advertising_id,traffic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
    }
}